package com.cskaoyan.service;

import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.wxbo.WxAddCartBo;
import com.cskaoyan.bean.wxbo.WxCartCheckedoutBo;
import com.cskaoyan.bean.wxbo.WxCartUpdateBo;
import com.cskaoyan.bean.wxvo.WxCartCheckoutVo;
import com.cskaoyan.bean.wxvo.WxCartListVo;
import com.cskaoyan.bean.wxvo.WxCartTotalBeanVo;
import com.cskaoyan.bean.wxvo.WxCouponVo;
import com.cskaoyan.mapper.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class WxCartServiceImpl implements WxCartService {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    MallCouponMapper mallCouponMapper;

    @Autowired
    MallCouponUserMapper mallCouponUserMapper;

    @Autowired
    WxCouponService wxCouponService;

    @Override
    public WxCartListVo getCartList(Integer userId) {


        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(true);

        List<Cart> carts = cartMapper.selectByExample(cartExample);

        if (carts == null || carts.size() == 0) {


            WxCartListVo wxCartListVo = new WxCartListVo();
            WxCartTotalBeanVo wxCartTotalBeanVo = new WxCartTotalBeanVo();
            wxCartTotalBeanVo.setGoodsCount(0);
            wxCartTotalBeanVo.setGoodsAmount(new BigDecimal(0));
            wxCartTotalBeanVo.setCheckedGoodsCount(0);
            wxCartTotalBeanVo.setCheckedGoodsAmount(new BigDecimal(0));
            wxCartListVo.setCartTotal(wxCartTotalBeanVo);
            return wxCartListVo;
        }
        int checkedGoodsCount = 0;
        int goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount = new BigDecimal(0);

        for (Cart cart : carts) {
            if (cart.getChecked()) {
                //勾选的购物车商品数
                checkedGoodsCount += cart.getNumber();

                //勾选的购物车价格
                BigDecimal goodsNumber = new BigDecimal(cart.getNumber());
                BigDecimal multiply = cart.getPrice().multiply(goodsNumber);
                checkedGoodsAmount = checkedGoodsAmount.add(multiply);

            }
            //购物车总的商品数
            goodsCount += cart.getNumber();
            //总的的购物车价格
            BigDecimal goodsNumber = new BigDecimal(cart.getNumber());
            BigDecimal multiply = cart.getPrice().multiply(goodsNumber);
            goodsAmount = goodsAmount.add(multiply);

        }

        WxCartTotalBeanVo wxCartTotalBeanVo = new WxCartTotalBeanVo();

        //封装total
        wxCartTotalBeanVo.setCheckedGoodsAmount(checkedGoodsAmount);
        wxCartTotalBeanVo.setCheckedGoodsCount(checkedGoodsCount);
        wxCartTotalBeanVo.setGoodsAmount(goodsAmount);
        wxCartTotalBeanVo.setGoodsCount(goodsCount);
        WxCartListVo wxCartListVo = new WxCartListVo();

        //封装数据
        wxCartListVo.setCartTotal(wxCartTotalBeanVo);
        wxCartListVo.setCartList(carts);

        return wxCartListVo;
    }

    @Override
    public WxCartListVo cartChecked(Integer userId, Integer[] productIds, Integer isChecked) {

        boolean b = false;
        int index = 0;
        for (Integer productId : productIds) {

            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andUserIdEqualTo(userId)
                    .andProductIdEqualTo(productId)
                    .andDeletedEqualTo(true);

            Cart cart = new Cart();

            if (isChecked == 1) b = true;
            cart.setChecked(b);

            int i = cartMapper.updateByExampleSelective(cart, cartExample);

            if (i == 1) index++;
        }

        if (index != productIds.length) return null;

        WxCartListVo cartList = getCartList(userId);
        return cartList;

    }


    @Override
    public int addCart(Integer userId, WxAddCartBo wxAddCartBo) {
        Cart cart = new Cart();
        //addtime和updatetime,deleted = 1默认,checked = 1 默认

        Date date = new Date();
        cart.setUserId(userId);
        cart.setAddTime(date);
        cart.setUpdateTime(date);
        cart.setDeleted(true);
        cart.setChecked(true);
        cart.setNumber((short) wxAddCartBo.getNumber());
        //根据wxAddCartBo.getGoodsId()查询goods的goods_sn,goods_name,pic_url

        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andIdEqualTo(wxAddCartBo.getGoodsId());

        List<Goods> goodss = goodsMapper.selectByExample(goodsExample);

        Goods goods = goodss.get(0);


        cart.setGoodsId(goods.getId());
        cart.setGoodsName(goods.getName());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setPicUrl(goods.getPicUrl());

        //根据productId查询product的price,
        GoodsProduct goodsProduct = new GoodsProduct();
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteria1 = goodsProductExample.createCriteria();
        criteria1.andIdEqualTo(wxAddCartBo.getProductId());
        criteria1.andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        GoodsProduct goodsProduct1 = goodsProducts.get(0);

        //赋值
        BigDecimal price = new BigDecimal(goodsProduct1.getPrice());

        cart.setPrice(price);
        cart.setProductId(goodsProduct1.getId());
        String[] specifications = goodsProduct1.getSpecifications();

        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {
            s = objectMapper.writeValueAsString(specifications);
        } catch (JsonProcessingException e) {
            System.out.println("出错了啊");
            return 0;
        }
        cart.setSpecifications(s);


        //根据userId和productId查询表中是否存在对应购物车，有就修改，没有就添加

        CartExample cartExample1 = new CartExample();
        CartExample.Criteria criteria3 = cartExample1.createCriteria();
        criteria3.andUserIdEqualTo(userId)
                .andProductIdEqualTo(goodsProduct1.getId())
                .andDeletedEqualTo(true);

        List<Cart> carts1 = cartMapper.selectByExample(cartExample1);
        if (carts1 != null && carts1.size() != 0) {

            System.out.println("更新旧的");

            cart = carts1.get(0);
            cart.setUpdateTime(date);

            //增加数量
            int i = cart.getNumber() + wxAddCartBo.getNumber();
            cart.setNumber((short) i);
            //修改价格
            Double price1 = goodsProduct1.getPrice();
            BigDecimal priceee = new BigDecimal(price1);
            BigDecimal multiply = priceee.multiply(BigDecimal.valueOf(i));
            cart.setPrice(multiply);

            //update
            int i1 = cartMapper.updateByExampleSelective(cart, cartExample1);

        } else {

            System.out.println("添加新的");
            int insert = cartMapper.insert(cart);
            if (insert == 0) return 0;

        }
        //根据userId查询cart购物车中的数量
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria2 = cartExample.createCriteria();
        criteria2.andUserIdEqualTo(userId);
        criteria2.andDeletedEqualTo(true);
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        Integer count = 0;
        for (Cart cart1 : carts) {
            count += cart1.getNumber();
        }

        return count;

    }

    @Override
    public boolean deleteCart(Integer userId, Integer[] productIds) {

        int i = 0;
        Date date = new Date();
        for (Integer productId : productIds) {

            int index = cartMapper.changeDeletedByUserIdAndProdectId(userId, productId, date);

            System.out.println(index);
            if (index == 1) i++;
        }

        if (i == productIds.length) return true;
        return false;
    }

    @Override
    public boolean updateCartForUpdate(WxCartUpdateBo wxCartUpdateBo, User currentUser) {

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(currentUser.getId())
                .andIdEqualTo(wxCartUpdateBo.getId())
                .andDeletedEqualTo(true);

        //符合id，deleted，productid的只有一个
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        Cart cart = carts.get(0);
        Short number1 = cart.getNumber();
        BigDecimal price = cart.getPrice();
        int i = wxCartUpdateBo.getNumber();
        cart.setNumber((short) i);
        BigDecimal divide = price.divide(BigDecimal.valueOf(number1));

        cart.setPrice(divide.multiply(BigDecimal.valueOf(i)));

        //
        int i1 = cartMapper.updateByExampleSelective(cart, cartExample);
        if (i1 == 1) return true;
        return false;

    }


    @Override
    public WxCartCheckoutVo checkedout(WxCartCheckedoutBo wxCartCheckedoutBo, User currentUser) {
        //需要返回的Vo
        WxCartCheckoutVo wxCartCheckoutVo = new WxCartCheckoutVo();

        List<Cart> carts = null;
        if(wxCartCheckedoutBo.getCartId()>0) {


            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andDeletedEqualTo(true)
                    .andIdEqualTo(wxCartCheckedoutBo.getCartId());

            carts = cartMapper.selectByExample(cartExample);

        }else {

            //查carts列表
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andDeletedEqualTo(true)
                    .andCheckedEqualTo(true)
                    .andUserIdEqualTo(currentUser.getId());

            carts = cartMapper.selectByExample(cartExample);
        }

        if(carts.size()<1)return null;
        //算出商品总价
        BigDecimal goodsTotalPrice = new BigDecimal(0);

        for (Cart cart : carts) {
            BigDecimal price = cart.getPrice();
            goodsTotalPrice = goodsTotalPrice.add(price);
        }

        wxCartCheckoutVo.setGoodsTotalPrice(goodsTotalPrice);

        //由addressId查Address列表
        if (wxCartCheckedoutBo.getAddressId() > 0) {
            AddressExample addressExample = new AddressExample();
            AddressExample.Criteria criteria1 = addressExample.createCriteria();
            criteria1.andIdEqualTo(wxCartCheckedoutBo.getAddressId());

            List<Address> addresses = addressMapper.selectByExample(addressExample);
            if (addresses.size() != 0) {
                Address address = addresses.get(0);
                //封装地址
                wxCartCheckoutVo.setCheckedAddress(address);
                wxCartCheckoutVo.setAddressId(address.getId());
            }
        }
        //封装价格
        wxCartCheckoutVo.setActualPrice(goodsTotalPrice);
        wxCartCheckoutVo.setOrderTotalPrice(goodsTotalPrice);

        //初始化coupon信息
        wxCartCheckoutVo.setCouponPrice(new BigDecimal(0));
        wxCartCheckoutVo.setCouponId(0);
        //根据Id查优惠券

        if (wxCartCheckedoutBo.getCouponId() > 0 && wxCartCheckedoutBo.getCouponId() != null) {

            MallCouponExample mallCouponExample = new MallCouponExample();
            MallCouponExample.Criteria criteria3 = mallCouponExample.createCriteria();
            criteria3.andIdEqualTo(wxCartCheckedoutBo.getCouponId());
            List<MallCoupon> mallCoupon = mallCouponMapper.selectByExample(mallCouponExample);

            MallCoupon currentMallCoupon = mallCoupon.get(0);

            BigDecimal discount = currentMallCoupon.getDiscount();

            //封装优惠的价格
            BigDecimal actualPrice = goodsTotalPrice.subtract(discount);
            wxCartCheckoutVo.setActualPrice(actualPrice);
            wxCartCheckoutVo.setOrderTotalPrice(actualPrice);

            //封装优惠劵参数
            wxCartCheckoutVo.setCouponPrice(discount);
            wxCartCheckoutVo.setCouponId(currentMallCoupon.getId());

        }


        //封装团购参数
        //不做团购，瞎写的
        wxCartCheckoutVo.setGrouponPrice(new BigDecimal(0));
        wxCartCheckoutVo.setGrouponRulesId(0);

        //
        List<WxCouponVo> wxCouponVos = wxCouponService.selectList(currentUser.getId());
        wxCartCheckoutVo.setAvailableCouponLength(wxCouponVos.size());

        if (wxCartCheckedoutBo.getCouponId() < 1) {
            wxCartCheckoutVo.setCouponId(-1);
        }
        //邮费,暂定为0
        wxCartCheckoutVo.setFreightPrice(new BigDecimal(0));
        wxCartCheckoutVo.setCheckedGoodsList(carts);

        System.out.println(wxCartCheckoutVo);
        return wxCartCheckoutVo;
    }


    @Override
    public int getGoodsGountByUserId(Integer userId) {

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(true)
                .andUserIdEqualTo(userId);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int count = 0;
        for (Cart cart : carts) {

            count += cart.getNumber();

        }

        return count;

    }

    @Override
    public int fastAddCart(Integer userId, WxAddCartBo wxAddCartBo) {

        Cart cart = new Cart();
        Date date = new Date();
        cart.setUserId(userId);
        cart.setAddTime(date);
        cart.setUpdateTime(date);
        cart.setDeleted(true);
        cart.setChecked(true);
        cart.setNumber((short) wxAddCartBo.getNumber());


        //查询goods
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andIdEqualTo(wxAddCartBo.getGoodsId());

        List<Goods> goodss = goodsMapper.selectByExample(goodsExample);

        Goods goods = goodss.get(0);
        cart.setGoodsId(goods.getId());
        cart.setGoodsName(goods.getName());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setPicUrl(goods.getPicUrl());


        //根据productId查询product的price,
        GoodsProduct goodsProduct = new GoodsProduct();
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteria1 = goodsProductExample.createCriteria();
        criteria1.andIdEqualTo(wxAddCartBo.getProductId());
        criteria1.andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        GoodsProduct goodsProduct1 = goodsProducts.get(0);

        //赋值
        BigDecimal price = new BigDecimal(goodsProduct1.getPrice());

        cart.setPrice(price);
        cart.setProductId(goodsProduct1.getId());
        String[] specifications = goodsProduct1.getSpecifications();

        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {
            s = objectMapper.writeValueAsString(specifications);
        } catch (JsonProcessingException e) {
            System.out.println("出错了啊");
            return 0;
        }
        cart.setSpecifications(s);


        //根据userId和productId查询表中是否存在对应购物车，有就修改，没有就添加

        CartExample cartExample1 = new CartExample();
        CartExample.Criteria criteria3 = cartExample1.createCriteria();
        criteria3.andUserIdEqualTo(userId)
                .andProductIdEqualTo(goodsProduct1.getId())
                .andDeletedEqualTo(true);

        List<Cart> carts1 = cartMapper.selectByExample(cartExample1);
        if (carts1 != null && carts1.size() != 0) {

            System.out.println("更新旧的");

            cart = carts1.get(0);
            cart.setUpdateTime(date);

            //增加数量
            int i = cart.getNumber() + wxAddCartBo.getNumber();
            cart.setNumber((short) i);
            //修改价格
            Double price1 = goodsProduct1.getPrice();
            BigDecimal priceee = new BigDecimal(price1);
            BigDecimal multiply = priceee.multiply(BigDecimal.valueOf(i));
            cart.setPrice(multiply);

            //update
            int i1 = cartMapper.updateByExampleSelective(cart, cartExample1);

        } else {

            System.out.println("添加新的");
            int insert = cartMapper.insert(cart);
            if (insert == 0) return 0;

        }


        return cart.getId();
    }
}
